from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import login, logout
import requests
import json


# 获取用户token
def get_access_token():
    headers = {'Content-Type': 'application/json'}
    get_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
    get_token_data = {
        "corpid": "corpid",          # 企业微信企业ID
        "corpsecret": "corpsecret"   # 企业微信应用Secret
    }
    r = requests.post(get_token_url, headers=headers, data=json.dumps(get_token_data))
    token = json.loads(r.text)['access_token']
    return token


# 用户登录首页，扫描login.html中的二维码
def logins(request):
    return render(request, 'wx_login_auth/login.html')

# 用户扫描完二维码认证通过后，跳转到该页面，先通过token及code获取userid，通过userid判断用户是否存在，接着做相应的跳转
def transfer(request):
    code = request.GET.get('code')
    token = get_access_token()
    request_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={}&code={}'.format(token, code)
    r = requests.get(url=request_url)
    print(r)
    username = 'wanglei'
    try:
        user = User.objects.get(username=username)
    except:
        return HttpResponse('用户不存在，请联系管理员')
    else:
        # 为用户浏览器设置cookie
        login(request, user)
        # 为用户浏览器清除cookie
        # logout(request)
        redirect_to = request.GET.get('next', '/wx/wx_index')
        return HttpResponseRedirect(redirect_to)

# 首页
@login_required
def index(request):
   return HttpResponse('hello，欢迎登录到运维平台')